package logic

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"short/internal/svc"
	"short/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowHandleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

var (
	Err404 = errors.New("404")
)

func NewShowHandleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowHandleLogic {
	return &ShowHandleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShowHandleLogic) ShowHandle(req *types.ShowReq) (resp *types.ShowResp, err error) {
	//使用布隆过滤器
	exist, err := l.svcCtx.Filter.Exists([]byte(req.ShortUrl))
	if err != nil {
		logx.Errorw("Filter.Exists failed", logx.LogField{Key: "err", Value: err})
	}
	//不存在
	if !exist {
		return nil, Err404
	}
	fmt.Println("开始查询缓存和数据.....")
	//查看短链接
	//使用了singleflight合并请求，防止缓存击穿
	data, err := l.svcCtx.ShortUrl.FindOneBySurl(l.ctx, sql.NullString{
		String: req.ShortUrl,
		Valid:  true,
	})
	if err != nil {
		logx.Errorw("hortUrl.FindOneBySurl failed", logx.LogField{Key: "err", Value: err})
		return nil, Err404
	}

	return &types.ShowResp{LongUrl: data.Lurl.String}, nil
}
